<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\WorkMoment\Queue;

use Hyperf\AsyncQueue\Annotation\AsyncQueueMessage;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Corp\Logic\AppTrait;
use MoChat\App\User\Contract\UserContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Plugin\WorkMoment\Contract\WorkMomentContract;
use MoChat\Plugin\WorkMoment\Contract\WorkMomentEmployeeContract;

/**
 * 企业微信 朋友圈成员发表状态
 * Class MomentTaskApply.
 */
class MomentTaskQueue
{
    use AppTrait;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeContract;

    /**
     * @Inject
     * @var WorkMomentContract
     */
    protected $workMomentContract;

    /**
     * @Inject
     * @var UserContract
     */
    protected $userContract;

    /**
     * @Inject
     * @var WorkMomentEmployeeContract
     */
    protected $workMomentEmployeeContract;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @AsyncQueueMessage(pool="default")
     * @param $corpId
     */
    public function handle($corpId): void
    {
        # #EasyWeChat获取「客户朋友圈-企业发表的列表」数据
        $list = $this->workMomentContract->getWorkMomentByCorpIdCreateType($corpId, 0, ['id', 'wx_moment_id']);
        $wx = $this->wxApp($corpId, 'contact')->external_contact_moment;
        foreach ($list as $item) {
            $result = $wx->getTasks($item['wxMomentId'], '', 1000);
            if ($result['errcode'] !== 0) {
                $this->logger->error('客户朋友圈获取员工列表失败' . Json::encode($result));
                continue;
            }

            # # 数据操作
            Db::beginTransaction();
            try {
                # # 创建朋友圈员工记录
                foreach ($result['task_list'] as $k => $v) {
                    $momentEmployee = $this->workMomentEmployeeContract->getWorkMomentEmployeeByWxMomentIdUserId($item['wxMomentId'], $v['userid']);
                    if (! empty($momentEmployee)) {
                        $this->workMomentEmployeeContract->updateWorkMomentEmployeeById($momentEmployee['id'], ['publish_status' => $v['publish_status']]);
                    } else {
                        $employee = $this->workEmployeeContract->getWorkEmployeeByCorpIdWxUserId((string) $corpId, $v['userid'], ['id', 'log_user_id']);
                        $data = [
                            'moment_id' => $item['id'],
                            'wx_moment_id' => $item['wxMomentId'],
                            'userid' => $v['userid'],
                            'publish_status' => $v['publish_status'],
                            'employee_id' => empty($employee) ? 0 : $employee[0]['id'],
                            'created_at' => date('Y-m-d H:i:s'),
                        ];
                        $this->workMomentEmployeeContract->createWorkMomentEmployee($data);
                    }
                }
                Db::commit();
            } catch (\Throwable $e) {
                Db::rollBack();
                $this->logger->error(sprintf('%s [%s] %s', '朋友圈员工创建失败', date('Y-m-d H:i:s'), $e->getMessage()));
                $this->logger->error($e->getTraceAsString());
                throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
            }
        }
    }
}
